"""
自定义中间件
"""

from django.conf import settings


class SecurityHeadersMiddleware:
    """
    安全头中间件
    确保所有响应都包含必要的安全头
    """
    
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        
        # 设置安全头
        response['X-Content-Type-Options'] = 'nosniff'
        # 不要全局覆盖X-Frame-Options，尊重Django设置/已有头部
        if 'X-Frame-Options' not in response:
            # 默认使用 settings.X_FRAME_OPTIONS（项目中为 SAMEORIGIN）
            response['X-Frame-Options'] = getattr(settings, 'X_FRAME_OPTIONS', 'SAMEORIGIN')
        response['X-XSS-Protection'] = '1; mode=block'
        response['Referrer-Policy'] = 'strict-origin-when-cross-origin'
        
        # 如果是登录页面，添加额外的安全头
        if request.path == '/login/' or request.path.startswith('/assets/login/'):
            response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
            response['Pragma'] = 'no-cache'
            response['Expires'] = '0'
        
        return response


class LoginSecurityMiddleware:
    """
    登录安全中间件
    为登录相关页面提供额外的安全保护
    """
    
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        
        # 如果是登录页面
        if request.path in ['/login/', '/assets/login/']:
            # 防止页面被缓存
            response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
            response['Pragma'] = 'no-cache'
            response['Expires'] = '0'
            
            # 防止页面被嵌入iframe
            response['X-Frame-Options'] = 'DENY'
            
            # 暂时移除CSP以避免兼容性问题
            # 如果需要CSP，可以在生产环境中启用更严格的策略
            # response['Content-Security-Policy'] = "default-src 'self' 'unsafe-inline'"
        
        return response